package com.learn.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class DruidConfiguration {
    /**
     * 配置DruidDataSource数据源，@ConfigurationProperties注解用于绑定并验证外部属性
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return new DruidDataSource();
    }
    
    /**
     * 后台监控Bean
     */
    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        // 后台监控访问视图和路径注册
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(
                new StatViewServlet(),
                "/druid/*"
        );
        
        // 后台监控访问用户密码配置
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "123456");
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        
        // 后台监控访问IP白名单
        servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
        
        // 后台监控访问IP黑名单
        servletRegistrationBean.addInitParameter("cj", "192.168.1.73");
        
        // 白名单与黑名单同时存在时，黑名单的优先级更高
        
        return servletRegistrationBean;
    }
    
    /**
     * 过滤器
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        // 过滤器注册
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        
        // 进行后台监控的过滤规则
        filterRegistrationBean.addUrlPatterns("/*");
        
        // 不进行后台监控的过滤规则
        filterRegistrationBean.addInitParameter("exclusions", "#.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        
        return filterRegistrationBean;
    }
}
